Calculated fields
One of the most good features of Delphi database programming is calculated fields.
By using calculated fields you can create new fields that does not exist in original
database tables. These fields can be displayed as any normal read-only fields. Example:
Suppose that you have two fields in your table: A, and B. Both fields are Integers.
Example of data:
A | B
--------
2 | 3
1 | 2
7 | 3
4 | 4
You need to display the summation of the two fields of one record in a new calculated
field to be displayed as:
A | B | C
--------------
2 | 3 | 5
1 | 2 | 3
7 | 3 | 10
4 | 4 | 8
To achive this follow below steps:
- Drop a table and link it with your table that contains A, and B fields.
- Double-click at Table1
- At fields editor right click and select Add all fields
- Right click again and select New Field
- At name box write C. At Type combo box select Integer. At field type select Calculated.
- Return to Table1 events and write below statement at OnCalcFields:
DataSet.FieldByName('C').AsInteger:=
DataSet.FieldByName('A').AsInteger + DataSet.FieldByName('B').AsInteger;
- Link your table with any data control such dbGrid and see the new calculated field.
Notes:
- Calculated fields can be used with any data sets including: BDE components, ADO
components, dbExpress, Interbase components. Example: TTable, TQuery, TADOTable,
TADOQuery, TIBTable, TIBQuery, etc.
- Calculated fields can be used with any data types